<template>
  <view class="container">
    <view class="navbar">
      <view class="navbar-title">添加复查项目</view>
    </view>
    
    <scroll-view class="content" scroll-y>
      <view class="form-item">
        <view class="form-label required">复查项目</view>
        <FormPicker 
          v-model="form.projectName" 
          :options="projectOptions" 
          placeholder="请选择复查项目"
          :required="false"
          @change="handleProjectChange"
        />
      </view>
      
      <!-- 其他项目输入框 -->
      <view class="form-item" v-if="form.projectName === '其它'">
        <view class="form-label required">复查项目名称</view>
        <FormInput 
          v-model="form.otherProjectName" 
          placeholder="请输入复查项目"
          :required="true"
        />
      </view>
      
      <view class="form-item">
        <view class="form-label required">复查时间</view>
        <DatePickerField 
          v-model="form.reviewTime" 
          placeholder="请选择复查时间"
          :required="true"
        />
      </view>
      
      <view class="form-item">
        <view class="form-label required">预约时间</view>
        <DatePickerField 
          v-model="form.appointmentTime" 
          placeholder="请选择预约时间"
          :required="true"
        />
      </view>
      
      <view class="form-item">
        <view class="form-label required">是否空腹</view>
        <FormPicker 
          v-model="form.isEmpty" 
          :options="emptyOptions" 
          placeholder="请选择是否空腹"
          :required="true"
        />
      </view>
    </scroll-view>
    
    <view class="confirm-button" @click="handleConfirmClick">
      <text>确认添加</text>
    </view>
    
    <!-- 确认添加对话框 -->
    <ConfirmDialog 
      title="提示" 
      content="您确认添加该复查项目吗？" 
      :visible="showDialog"
      @confirm="submitForm"
      @cancel="showDialog = false"
    ></ConfirmDialog>
    
    <!-- 订阅消息确认对话框 -->
    <ConfirmDialog 
      title="消息订阅" 
      content="是否允许接收复查提醒消息？" 
      :visible="needSubscribe"
      @confirm="handleSubscribeConfirm"
      @cancel="handleSubscribeCancel"
    ></ConfirmDialog>
  </view>
</template>

<script>
import FormPicker from '../../components/FormPicker.vue';
import FormInput from '../../components/FormInput.vue';
import DatePickerField from '../../components/DatePickerField.vue';
import ConfirmDialog from '../../components/ConfirmDialog.vue';
import config from '../../config.js';

export default {
  components: {
    FormPicker,
    FormInput,
    DatePickerField,
    ConfirmDialog
  },
  data() {
    return {
      form: {
        projectName: null,
        otherProjectName: '',
        reviewTime: '',
        appointmentTime: '',
        isEmpty: null
      },
      projectOptions: ['甲功', '血钙', '颈部超声', '其它'],
      emptyOptions: ['是', '否'],
      showDialog: false,
      needSubscribe: false, // 新增：标记是否需要显示订阅确认
      openid: '',
      hospitalNumber: uni.getStorageSync('hospitalNumber') || ''
    };
  },
  methods: {
    navigateBack() {
      uni.navigateBack();
    },
    
    handleProjectChange() {
      if (this.form.projectName !== '其它') {
        this.form.otherProjectName = '';
      }
    },
    
    handleConfirmClick() {
      if (this.validateForm()) {
        this.showDialog = true;
      }
    },
    
    validateForm() {
      // 验证逻辑保持不变
      const { projectName, otherProjectName, reviewTime, appointmentTime, isEmpty } = this.form;
      const errors = [];
      
      if (!projectName) {
        errors.push('请选择复查项目');
      } else if (projectName === '其它' && !otherProjectName) {
        errors.push('请输入复查项目名称');
      }
      
      if (!reviewTime) {
        errors.push('请选择复查时间');
      } else {
        const now = new Date();
        now.setHours(0, 0, 0, 0);
        const reviewDate = new Date(reviewTime);
        reviewDate.setHours(0, 0, 0, 0);
        
        if (reviewDate < now) {
          errors.push('复查时间必须晚于或等于当前天数');
        }
      }
      
      if (!appointmentTime) {
        errors.push('请选择预约时间');
      } else {
        const now = new Date();
        now.setHours(0, 0, 0, 0);
        const appointmentDate = new Date(appointmentTime);
        appointmentDate.setHours(0, 0, 0, 0);
        const reviewDate = new Date(reviewTime);
        reviewDate.setHours(0, 0, 0, 0);
        
        if (appointmentDate < now) {
          errors.push('预约时间必须晚于或等于当前天数');
        }
        
        if (appointmentDate > reviewDate) {
          errors.push('预约时间必须早于复查时间');
        }
      }
      
      if (isEmpty === null) {
        errors.push('请选择是否空腹');
      }
      
      if (errors.length > 0) {
        uni.showToast({
          title: errors.join('；'),
          icon: 'none',
          duration: 3000
        });
        return false;
      }
      
      return true;
    },
    
    // 获取用户openid方法（修改：移除自动调用订阅授权）
    async getOpenid() {
      console.log('===== 开始获取OpenID =====');
      try {
        // 调用微信登录接口获取code
        console.log('调用uni.login获取code...');
        const { code } = await uni.login({});
        console.log('获取code成功:', code);
        
        // 调用后端接口换取openid
        console.log('调用后端接口换取openid，请求参数:', {
          code,
          hospitalNumber: this.hospitalNumber
        });
        const res = await uni.request({
          url: `${config.baseUrl}/messageAlert/getOpenid`,
          method: 'POST',
          header: {
            'Content-Type': 'application/json',
            'Authorization': uni.getStorageSync('token') || ''
          },
          data: {
            code,
            hospitalNumber: this.hospitalNumber
          }
        });
        
        console.log('后端返回结果:', res);
        if (res.statusCode === 200 && res.data.code === 200) {
          this.openid = res.data.openid;
          console.log('获取OpenID成功:', this.openid);
          // 移除：不再在这里自动调用订阅授权
        } else {
          console.error('获取OpenID失败，后端返回码:', res.data?.code || res.statusCode);
          uni.showToast({
            title: '获取OpenID失败',
            icon: 'none'
          });
          return false; // 获取失败返回false
        }
        return true; // 获取成功返回true
      } catch (error) {
        console.error('获取OpenID过程发生异常:', error);
        uni.showToast({
          title: '网络错误',
          icon: 'none'
        });
        return false; // 发生异常返回false
      } finally {
        console.log('===== 获取OpenID流程结束 =====');
      }
    },
    
    // 请求消息订阅授权并发送消息（保持不变）
    async requestMessageSubscription() {
      console.log('===== 开始请求消息订阅授权 =====');
      try {
        const templateId = 'vBmViwOe2te9Ds_j_j9thy3G6micG6gzmmtnsgclpfY';
        // 调用微信订阅消息接口
        console.log('调用uni.requestSubscribeMessage，模板ID:', templateId);
        const res = await uni.requestSubscribeMessage({
          tmplIds: [templateId]
        });
        
        console.log('订阅授权结果:', res);
        // 判断用户是否同意订阅
        if (res[templateId] === 'accept') {
          console.log('用户已同意订阅，调用后端保存授权记录接口');
          // 调用后端接口保存授权信息
          const saveRes = await uni.request({
            url: `${config.baseUrl}/messageAlert/addAuthority`,
            method: 'POST',
            header: {
              'Content-Type': 'application/json',
              'Authorization': uni.getStorageSync('token') || ''
            },
            data: {
              openid: this.openid,
              hospitalNumber: this.hospitalNumber
            }
          });
          
          console.log('后端保存授权记录结果:', saveRes);
          if (saveRes.statusCode === 200 && saveRes.data.code === 200) {
            console.log('授权记录保存成功，准备发送订阅消息');
            // 调用后端发送消息接口
            await this.sendSubscribeMessage();
          } else {
            console.error('保存授权记录失败:', saveRes.data?.msg);
            uni.showToast({
              title: '授权记录保存失败',
              icon: 'none'
            });
          }
        } else if (res[templateId] === 'reject') {
          console.log('用户拒绝订阅消息');
          uni.showToast({
            title: '您已拒绝订阅消息',
            icon: 'none'
          });
        } else if (res[templateId] === 'ban') {
          console.log('用户已被禁止订阅消息');
          uni.showToast({
            title: '您已禁止接收订阅消息',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('订阅授权过程发生异常:', error);
        uni.showToast({
          title: '订阅消息请求失败',
          icon: 'none'
        });
      } finally {
        console.log('===== 消息订阅授权流程结束 =====');
      }
    },
    
    // 调用后端发送订阅消息接口（保持不变）
    async sendSubscribeMessage() {
      console.log('===== 开始发送订阅消息 =====');
      try {
        const templateId = 'vBmViwOe2te9Ds_j_j9thy3G6micG6gzmmtnsgclpfY';
        console.log('调用后端发送消息接口，参数:', {
          openid: this.openid,
          templateId,
          thing1: '测试成功',
          thing8: '恭喜测试成功'
        });
        
        const res = await uni.request({
          url: `${config.baseUrl}/messageAlert/sendMessage`,
          method: 'POST',
          header: {
            'Content-Type': 'application/json',
            'Authorization': uni.getStorageSync('token') || ''
          },
          data: {
            openid: this.openid,
            templateId: templateId,
            data: {
              thing1: '测试成功', // 活动名称
              thing8: '恭喜测试成功' // 温馨提示
            }
          }
        });
        
        console.log('后端发送消息结果:', res);
        if (res.statusCode === 200 && res.data.code === 200) {
          console.log('订阅消息发送成功');
          uni.showToast({
            title: '订阅消息已发送',
            icon: 'success'
          });
        } else {
          console.error('订阅消息发送失败:', res.data?.msg);
          uni.showToast({
            title: '消息发送失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('发送消息过程发生异常:', error);
        uni.showToast({
          title: '消息发送失败',
          icon: 'none'
        });
      } finally {
        console.log('===== 发送订阅消息流程结束 =====');
      }
    },
    
    // 新增：处理用户确认订阅
    async handleSubscribeConfirm() {
      this.needSubscribe = false;
      // 在用户点击事件中直接调用订阅授权
      await this.requestMessageSubscription();
      
      // 订阅流程完成后返回上一页
      setTimeout(() => {
        uni.navigateBack();
      }, 1000);
    },
    
    // 新增：处理用户取消订阅
    handleSubscribeCancel() {
      this.needSubscribe = false;
      // 取消订阅后也返回上一页
      setTimeout(() => {
        uni.navigateBack();
      }, 500);
    },
    
    // 提交表单方法（修改：调整订阅流程）
    submitForm() {
      this.showDialog = false;
      
      const hospitalNumber = uni.getStorageSync('hospitalNumber');
      const projectName = this.form.projectName === '其它' 
        ? this.form.otherProjectName 
        : this.form.projectName;
      
      const formData = {
        hospitalNumber,
        projectName,
        reviewTime: this.form.reviewTime,
        appointmentTime: this.form.appointmentTime,
        isEmpty: this.form.isEmpty
      };
      
      console.log('开始提交复查项目表单:', formData);
      uni.request({
        url: `${config.baseUrl}/puwai/addReviewInfo`,
        method: 'POST',
        data: formData,
        header: {
          'Content-Type': 'application/json',
          'Authorization': uni.getStorageSync('token') || ''
        },
        success: async (res) => {
          console.log('添加复查项目接口返回:', res);
          if (res.data && res.data.code === 1) {
            uni.showToast({
              title: '成功添加复查项目',
              icon: 'success',
              duration: 1500
            });
            
            // 先获取OpenID，成功后显示订阅确认对话框
            const openidSuccess = await this.getOpenid();
            if (openidSuccess) {
              // 显示订阅确认对话框，等待用户主动点击
              setTimeout(() => {
                this.needSubscribe = true;
              }, 1500);
            } else {
              // 获取OpenID失败，直接返回上一页
              setTimeout(() => {
                uni.navigateBack();
              }, 1500);
            }
          } else {
            uni.showToast({
              title: res.data.msg || '添加失败',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          console.error('添加复查项目失败:', err);
          uni.showToast({
            title: '添加失败',
            icon: 'none'
          });
        }
      });
    }
  }
};
</script>

<style scoped>
/* 样式保持不变 */
.container {
  background-color: #f8f9fa;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.navbar {
  height: 44px;
  background-color: #1677ff;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 16px;
}

.navbar-title {
  font-size: 17px;
  font-weight: bold;
}

.content {
  flex: 1;
  padding: 20rpx;
}

.form-item {
  margin-bottom: 20rpx;
  background-color: #fff;
  padding: 20rpx;
  border-radius: 10rpx;
}

.form-label {
  font-size: 30rpx;
  color: #333;
  margin-bottom: 10rpx;
  display: inline-block;
}

.required::after {
  content: '*';
  color: #ff4d4f;
  margin-left: 5rpx;
}

.confirm-button {
  height: 100rpx;
  background-color: #1677ff;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 36rpx;
  margin: 20rpx;
  border-radius: 10rpx;
  opacity: 1;
  transition: opacity 0.2s;
}

.confirm-button:active {
  opacity: 0.8;
}
</style>
